using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;


namespace SCore.Editor.BuildPackage
{
    public class BuildPipelineUtils
    {
        #region enums

        public static class SChannelType
        {
            public static readonly string Windows = "windows";
            public static readonly string GooglePlay = "googleplay";
            public static readonly string AppStore = "appstore";
        }

        public static class SPlatformType
        {
            public static readonly string Windows = "windows";
            public static readonly string MacOSX = "macOSX";

            public static readonly string Android = "android";
            public static readonly string IOS = "ios";
        }

        public static class STargetType
        {
            public static readonly string Develop = "dev";
            public static readonly string Release = "release";
        }

        #endregion

        #region Version

        public static TimeSpan GetTimeSpan()
        {
            var span = DateTime.Now - new DateTime(2022, 1, 1, 0, 0, 0);
            return span;
        }

        public static string GenerateTimeStampVersion(string version, int timestamp)
        {
            CheckVersion(version);
            return version + "." + GetMinorVersion(timestamp);
        }

        private static int GetMinorVersion(int timestamp)
        {
            return timestamp / 10;
        }

        public static void CheckVersion(string version)
        {
            string[] ss = version.Split('.');
            if (ss.Length != 2)
                throw new Exception(string.Format("Version {0} Format Error!", version));
        }

        #endregion

        #region Addressable

        // 通过代码设置remoteBuildDir
        // 目前需要存在才能更新
        public static void SetRemoteLoadPathForJenkinsByCode()
        {
            var profileSettings = AddressableAssetSettingsDefaultObject.Settings.profileSettings;

            var platform = EditorUserBuildSettings.activeBuildTarget.ToString().ToLower();
            Dictionary<string, string> profileIdToRemoteBuildDir = new Dictionary<string, string>()
            {
                { "dev", $"http://10.0.84.152:8081/xnext/{platform}" },
                // pro fallback 策略
                // makerx-cdn-us.akamaized.net --> makerx-global-cdn.centurygame.com
                { "pro", $"https://makerx-cdn-us.akamaized.net/xnext/pro/{platform}" },
            };

            // range profileIdToRemoteBuildDir
            foreach (var (k, v) in profileIdToRemoteBuildDir)
            {
                var profileId = profileSettings.GetProfileId(k);
                var old =
                    profileSettings.GetValueByName(profileId, AddressableAssetSettings.kRemoteLoadPath);
                profileSettings.SetValue(profileId, AddressableAssetSettings.kRemoteLoadPath, v);
                ("[BuildPipeline]:SetRemoteLoadPathForJenkinsByCode " +
                 $"{k} {old} => {v}").Log();
            }

            profileSettings.SetDirty(AddressableAssetSettings.ModificationEvent.ProfileModified, null, true);

            // 禁用自动更新
            AddressableAssetSettingsDefaultObject.Settings.DisableCatalogUpdateOnStartup = true;
            "DisableCatalogUpdateOnStartup set to true".Log();
            EditorUtility.SetDirty(AddressableAssetSettingsDefaultObject.Settings);
            AssetDatabase.SaveAssets();
        }

        #endregion

        #region defines

        public static HashSet<string> GetScriptingDefineSymbols(BuildTargetGroup targetGroup)
        {
            var defineSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
            var arr = defineSymbols.Split(';');
            var result = new HashSet<string>();
            foreach (var iter in arr) result.Add(iter);
            return result;
        }

        public static void SetScriptingDefineSymbols(BuildTargetGroup targetGroup, HashSet<string> arr)
        {
            var sb = new StringBuilder();
            foreach (var iter in arr)
            {
                sb.Append(";");
                sb.Append(iter);
            }

            var defines = sb.ToString();
            if (string.IsNullOrEmpty(defines)) return;
            $"[BuildPackage] Build SetScriptingDefineSymbols: {defines}".Log();
            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, defines.Substring(1));
        }

        #endregion


        public static void CopyAboutAssets(UnityEditor.BuildTarget buildTarget, bool needAddressableOverride)
        {
            //字体文件
            //CopyTMPSettings();
            //热更新DLL处理

            /***
            AssembliesUtils.GenerateAllHotUpdateDLL(buildTarget, needAddressableOverride);
            //shader变体收集
            ShaderVariantAutoCollection.GenerateShaderVariants.GenerateAllSVCs();
            //重新导入文件时的刷新
            var autoSettings = AutoGroupSetting.Instance;
            var assetPaths = new List<string>()
            {
                autoSettings._autoGroupRoot,
            };
            //重新导入资源
            AutoGroupImporter.ReimportFolders(assetPaths, autoSettings);
            //添加shader资源组
            AutoGroupImporter.AddShaderToGroup();
            ***/
        }
    }
}